import socket
import pickle
import sys

class O2SClient:
    def __init__(self, host, port):
        self.host = host
        self.port = port
        
    def save_data_to_file(self, file, data):
        # Запись блока данных в файл
        if data[0] == 2 and data[1] == "FD":
            file.write(data[3])

    def get_file(self, filename):
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
                client_socket.connect((self.host, self.port))
                # Запрос файла
                get_request = pickle.dumps(["GET", filename])
                client_socket.sendall(get_request)
                # Открытие файла на запись
                with open(filename, "wb") as file:
                    while True:
                        data = client_socket.recv(1024)
                        if not data:
                            break
                        packet = pickle.loads(data)
                        self.save_data_to_file(file, packet)
                        if packet[0] == "END":
                            break
        except Exception as e:
            print(f"Произошла ошибка: {e}")
            sys.exit(1)
